package keeto.com.vn.classified.ui;

import it.sephiroth.android.library.widget.AbsHListView;
import it.sephiroth.android.library.widget.AbsHListView.OnScrollListener;
import it.sephiroth.android.library.widget.HListView;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.androidquery.AQuery;
import com.androidquery.util.AQUtility;

import keeto.com.vn.classfied.model.Area;
import keeto.com.vn.classfied.model.Category;
import keeto.com.vn.classified.adapter.HomeProductAdapter;
import keeto.com.vn.classified.adapter.ProductCategoriesAdapterManager;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.database.BuiltinService;
import keeto.com.vn.classified.database.BuiltinServiceManager;
import keeto.com.vn.classified.manager.IAManager;
import keeto.com.vn.classified.menutab.IMenuTabConfig;
import keeto.com.vn.classified.menutab.MenuTabAdapter;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.network.entity.ListItemEntity;
import keeto.com.vn.classified.utils.UtilityListView;
import keeto.com.vn.classified.widgets.LogoutDialog;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class SubCategoriesActivity extends Activity implements
OnClickListener, OnItemClickListener {

	private final static String EXTRA_PARENT_CATEGORY = "ParentCategory";
	private final static String EXTRA_SELECTED_AREA = "SelectedArea";
	private final static int PAGELIMIT=10;

	public final static int REQUEST_SEARCH = 1;
	private TextView thinnertitle;
	private ProgressBar pg;
	private int type = ProductCategoriesAdapterManager.ADAPTER_SUB_CATEGORY;
	private ProductCategoriesAdapterManager adapetMng = null;
	private ListView lvSubCategory = null;
	private Category mParentCate = null;
	private Area mArea = null;
	private Vector<Category> childList = null;
	private String mAction = null;
	private ViewPager hppager;
	private IANewHomeListener mListener1 = new IANewHomeListener();
	private TextView view_all;

	private Button btn_editor_warranty;
	private EditText edt_search_warranty_store;
	private ImageButton btn_search_warranty;

	private ImageButton ib_title_na_menu;
	private ImageButton ib_title_logo_home;
	private ImageView iv_title_search_home;

	private	DrawerLayout drawerLayoutMenuTab;
	private ListView mDrawerList;

	BuiltinServiceManager mBuiltinServiceManager = null;
	private  BuiltinService builtservice = null;
	private MenuTabAdapter tabAdapter;
	private int position;
	private static InUIThreadHandler mReturnCodeHandler = null;
	private HomeProductAdapter SuggestAdapter;
	private HListView hListView_Product;
	private View footerView;
	private ProgressBar pb_pg_load_bottom;
	private int PageNumber = 1;
	private int PageCount = 1;
	private int sortby = 5;
	private String Area = "1";
	private AQuery aQuery;


	private ArrayList<ListItemEntity> arrSusgest = new ArrayList<ListItemEntity>();

	public static void getIntentView(Activity context, Category category, 
			Area area, int position) {
		Intent i = new Intent(context, SubCategoriesActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		i.setAction(CategoriesActivity.CMD_CATEGORIES_VIEW);
		i.putExtra(EXTRA_SELECTED_AREA, area);
		i.putExtra("position", position);
		i.putExtra(EXTRA_PARENT_CATEGORY, category);
		context.startActivityForResult(i, 1);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ia_sub_category);//product_cate_3
		mReturnCodeHandler = new InUIThreadHandler();
		mBuiltinServiceManager = BuiltinServiceManager.getInstance(SubCategoriesActivity.this);
		builtservice = mBuiltinServiceManager.getBuitinService();
		Intent i = getIntent();
		Bundle extras = i.getExtras();
		aQuery = new AQuery(this);
		mAction = i.getAction();
		mArea = (Area) extras.get(EXTRA_SELECTED_AREA);
		mParentCate = (Category) extras.get(EXTRA_PARENT_CATEGORY);
		position = (Integer) extras.get("position");
		initUIComponent();
		initMenuData();
		ClassifiedCore.getInstance(SubCategoriesActivity.this).taskGetAndroidProductProposed(mListener1, Area, "",sortby+"", PAGELIMIT, PageNumber, "products", mParentCate.getRemoteId());
	}

	@Override
	public void onBackPressed() {
		if (drawerLayoutMenuTab.isDrawerOpen(mDrawerList)) {
			drawerLayoutMenuTab.closeDrawers();
			return;
		}else {
			super.onBackPressed();

		}
	}

	private void initUIComponent(){
		drawerLayoutMenuTab = (DrawerLayout)findViewById(R.id.drawer_layout);
		mDrawerList = (ListView)findViewById(R.id.drawer);

		ib_title_na_menu = (ImageButton) findViewById(R.id.btn_title_na_menu);
		ib_title_logo_home = (ImageButton) findViewById(R.id.btn_title_logo_home);
		iv_title_search_home = (ImageView) findViewById(R.id.btn_title_search_home);
		ib_title_na_menu.setOnClickListener(this);
		ib_title_logo_home.setOnClickListener(this);
		iv_title_search_home.setOnClickListener(this);
		pg = (ProgressBar) findViewById(R.id.loading);
		thinnertitle = (TextView) findViewById(R.id.thinner_title);
		thinnertitle.setOnClickListener(this);
		view_all = (TextView) findViewById(R.id.view_all);
		view_all.setOnClickListener(this);
		btn_editor_warranty = (Button) findViewById(R.id.btn_editor_warranty);
		btn_editor_warranty.setHint(mParentCate.getName());
		btn_editor_warranty.setOnClickListener(this);

		edt_search_warranty_store = (EditText) findViewById(R.id.edt_search_warranty_store);
		edt_search_warranty_store.setHint(mParentCate.getName());
		edt_search_warranty_store.setInputType(TRIM_MEMORY_COMPLETE);
		edt_search_warranty_store.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
					String keysearch = edt_search_warranty_store.getText().toString();
					ProductsActivity.actionSearchByCategory(SubCategoriesActivity.this, mParentCate.getRemoteId(), keysearch);
				}
				return false;
			}
		});
		btn_search_warranty = (ImageButton) findViewById(R.id.btn_search_warranty);
		btn_search_warranty.setOnClickListener(this);
		hListView_Product = (HListView) findViewById(R.id.HList_home_product);
		SuggestAdapter = new HomeProductAdapter(this,arrSusgest,aQuery);
		hListView_Product.setAdapter(SuggestAdapter);
		hListView_Product.setOnItemClickListener(new it.sephiroth.android.library.widget.AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(it.sephiroth.android.library.widget.AdapterView<?> parent, View view, int position, long id) {
				IADetailProductActivity.actionLaunchProduct(SubCategoriesActivity.this, (ListItemEntity) SuggestAdapter.getItem(position));
			}
		});

		footerView =  ((LayoutInflater) SubCategoriesActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
		hListView_Product.addFooterView(footerView);
		pb_pg_load_bottom = (ProgressBar) footerView.findViewById(R.id.pg_load_bottom);
		hListView_Product.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsHListView view, int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					if(PageNumber < PageCount){
						PageNumber++;
						ClassifiedCore.getInstance(SubCategoriesActivity.this).taskGetAndroidProductProposed(mListener1, Area, "","5", PAGELIMIT, PageNumber, "products", mParentCate.getRemoteId());
						pb_pg_load_bottom.setVisibility(View.VISIBLE);
					}
					break;
				default:
					break;
				}
			}
			@Override
			public void onScroll(AbsHListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {}
		});


		lvSubCategory = (ListView) findViewById(R.id.sub_category_list);
		childList = IAManager.getInstance(this).getViewCategory(mParentCate.getRemoteId());
		adapetMng = ProductCategoriesAdapterManager.getInstance(SubCategoriesActivity.this, childList, mAction);
		lvSubCategory.setAdapter(adapetMng.getAdapterByType(type));
		adapetMng.notifyDataChanged(childList);
		lvSubCategory.setOnItemClickListener(this);
		UtilityListView.setListViewHeightBasedOnChildrenforList(this,lvSubCategory);

	}



	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		childList.get(position);
		if (mAction.equals(CategoriesActivity.CMD_CATEGORIES_VIEW)) {
			IAProductCateIndexActivity.getIntentView(SubCategoriesActivity.this, mParentCate, mArea,  childList.get(position));
		}
	}


	public void addStringArrayToList(String[] array, List<String> strings) {
		if (array != null) {
			if (strings == null) {
				strings = new ArrayList<String>();
			}
			for (String str : array) {
				strings.add(str);
			}
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if (h != null) {
			h.removeCallbacks(animateViewPager);
		}
	}
	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	public void onResume() {
		super.onResume();
		mBuiltinServiceManager = BuiltinServiceManager.getInstance(SubCategoriesActivity.this);
		builtservice = mBuiltinServiceManager.getBuitinService();
		initMenuData();
		if (tabAdapter != null){
			for (int i=0;i<tabAdapter.getTabModel().size();i++){
				if (tabAdapter.getTabModel().get(i).getMenutab_key() == IMenuTabConfig.MENU_HOME){
					tabAdapter.getTabModel().get(i).setNameMenu(mParentCate.getName());
					break;
				}
			}
			tabAdapter.notifyDataSetChanged();
		}
		
	}
	@Override
	protected void onStop() {
		super.onStop();
	}

	private boolean pagerMoved = false;
	private static final long ANIM_VIEWPAGER_DELAY = 5000;
	private Handler h = new Handler();
	private Runnable animateViewPager = new Runnable() {
		public void run() {
			if (!pagerMoved) {
				try{
					if (hppager.getCurrentItem() < hppager.getAdapter().getCount() - 1) {
						hppager.setCurrentItem(hppager.getCurrentItem() + 1, true);
					} else {
						hppager.setCurrentItem(0, true);
					}
					h.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
				}catch (Exception e) {
				}

			} else {
				h.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
			}
		}
	};

	class IANewHomeListener extends ClassifiedListener{
		@Override
		public void finishgetAndroidProductProposed(final int returnCode,
				ArrayList<ListItemEntity> listPromotions,
				ArrayList<ListItemEntity> listSuggest,
				final ArrayList<ListItemEntity> listSuggestProduct,
				ArrayList<ListItemEntity> listFavorite, final boolean hasMore, final int PageCount) {
			super.finishgetAndroidProductProposed(returnCode, listPromotions, listSuggest, listSuggestProduct, listFavorite, hasMore, PageCount);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					pb_pg_load_bottom.setVisibility(View.GONE);
					pg.setVisibility(View.GONE);
					if (returnCode == IProtocol.STATUS_CODE_OK_200){
						SubCategoriesActivity.this.PageCount = PageCount;
						if (listSuggestProduct!= null && listSuggestProduct.size()>0){
							arrSusgest.addAll(listSuggestProduct);
							SuggestAdapter.notifyDataSetChanged();
						}

					}else{
						mReturnCodeHandler.takeActionByReturnCode(SubCategoriesActivity.this, returnCode, true);
					}
				}
			});
		}
	}
	private void initMenuData(){
		if (builtservice == null){
			tabAdapter = new MenuTabAdapter(SubCategoriesActivity.this, false,IMenuTabConfig.MENU_HOME);
		}else{
			tabAdapter = new MenuTabAdapter(SubCategoriesActivity.this, true,IMenuTabConfig.MENU_HOME);
			tabAdapter.setUsername(builtservice.getUserName());
		}
		mDrawerList.setAdapter(tabAdapter);
		mDrawerList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (tabAdapter.getTabModel() != null){
					int index = tabAdapter.getTabModel().get(position).getMenutab_key();
					switch (index) {
					case IMenuTabConfig.MENU_HOME:
						drawerLayoutMenuTab.closeDrawers();
						CategoriesActivity.launchCategoriesView(SubCategoriesActivity.this, mArea);
						break;
					case IMenuTabConfig.MENU_AREA:
						drawerLayoutMenuTab.closeDrawers();
						ProvincesActivity.actionChangeCityLaunch(SubCategoriesActivity.this);
						break;
					case IMenuTabConfig.MENU_PROFILE_NAME:
						if(builtservice==null){
							drawerLayoutMenuTab.closeDrawers();
							LoginActivity.actionLaunch(SubCategoriesActivity.this);
						}else{
							drawerLayoutMenuTab.closeDrawers();
							UserProfileActivity.actionLaunch(SubCategoriesActivity.this);
						}

						break;
					case IMenuTabConfig.MENU_INTEREST:
						drawerLayoutMenuTab.closeDrawers();
						FavoritesActivity.actionViewFavorites(SubCategoriesActivity.this);
						break;
					case IMenuTabConfig.MENU_POSTED:
						drawerLayoutMenuTab.closeDrawers();
						FavoritesActivity.actionViewPosted(SubCategoriesActivity.this);
						break;
					case IMenuTabConfig.MENU_HISTORY:
						drawerLayoutMenuTab.closeDrawers();
						FavoritesActivity.actionViewHistory(SubCategoriesActivity.this);

						break;
					case IMenuTabConfig.MENU_LOGOUT:
						drawerLayoutMenuTab.closeDrawers();
						LogoutDialog dialog= new LogoutDialog(SubCategoriesActivity.this);
						dialog.show();
						break;

					case IMenuTabConfig.MENU_POST:
						drawerLayoutMenuTab.closeDrawers();
						PostProductActivity.actionLaunch(SubCategoriesActivity.this);
						break;

					default:
						break;
					}

				}
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == ProvincesActivity.ACTION_CHANGE_AREA && resultCode == RESULT_OK){
			mArea =  IAManager.getInstance(this).getMyArea();
			if (tabAdapter != null && mArea != null){
				for (int i=0;i<tabAdapter.getTabModel().size();i++){
					if (tabAdapter.getTabModel().get(i).getMenutab_key() == IMenuTabConfig.MENU_AREA){
						tabAdapter.getTabModel().get(i).setNameMenu(mArea.getName());
						break;
					}
				}
				tabAdapter.notifyDataSetChanged();
			}
		}
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_title_na_menu:
			if (drawerLayoutMenuTab.isDrawerOpen(mDrawerList)) {
				drawerLayoutMenuTab.closeDrawers();
			} else {
				drawerLayoutMenuTab.openDrawer(mDrawerList);
			}
			break;
		case R.id.btn_title_search_home:
			ProductsActivity.actionSearchGlobal(this);
			break;
		case R.id.btn_title_logo_home:
			HomeClassifeldActivity.actionLaunch(SubCategoriesActivity.this);
			break;
		case R.id.btn_editor_warranty:
			CategoriesActivity.launchCategoriesView(SubCategoriesActivity.this, mArea);
			break;
		case R.id.thinner_title:
			IAProductCateIndexActivity.getIntentView(SubCategoriesActivity.this, mParentCate, mArea, null);
			break;
		case R.id.view_all:
			ListCateproductActivity.actionLaunchCateName(SubCategoriesActivity.this, SubCategoriesActivity.this.getResources().getString(R.string.ia_raovat_product_suggestions), mParentCate);//(SubCategoriesActivity.this, "Sản phẩm đề xuất");
			break;
		case R.id.btn_search_warranty:
			String keysearch = edt_search_warranty_store.getText().toString();
			ProductsActivity.actionSearchByCategory(SubCategoriesActivity.this, mParentCate.getRemoteId(), keysearch);
			break;
		default:
			break;
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(isTaskRoot()){

			long triggerSize = 3000000; 
			long targetSize = 2000000;      
			AQUtility.cleanCacheAsync(this, triggerSize, targetSize);
		}
	}
}
